% Matlab Code for replication of "Optimal Debt Maturity and Firm Investment"
% by J. Jungherr and I. Schott, September 2020
% This code solves the counterfactual model without debt dilution and debt
% overhang
function solve_model(PARMS)  

% Setup
VAL.period              = 1;
VAL.HISTORY             = cell(1,1);

setup_matrices % Creates empty matrices

% Solve period T-1
solve_T_1

% Iterate forward solution of T-1 in order to generate approximate values for bond price and value function 
simulate_V

% Solve period T-x
for oo = 1:599
    solve_T_x
end

%% Compute model moments

% Compute stationary distribution
stationary_dist

% Compute model moments
model_moments


%% Collect output for Table 5

% 1) Average firm leverage
Tab5_LTDce.meanlev      = 100*modelmoms.leverage.mean;
% 2) Average default rate
Tab5_LTDce.defrate      = 100*moment.defrate;
% 3) Average credit spread on LTD
Tab5_LTDce.meanspread   = 100*modelmoms.ltd_spread.mean;
% 4) Average LTD share
Tab5_LTDce.LTDshare     = 100*modelmoms.ltd_share.mean;

% Real variables
Tab5_LTDce.AvgK         = moment.AvgK;
Tab5_LTDce.AggK         = moment.AggK;
Tab5_LTDce.GDP          = moment.GDP;
Tab5_LTDce.Cons         = moment.Cons;
    
% Save model output
filename            = sprintf('%s%s','Tab5_LTDce','.mat');
fullname            = fullfile(PARMS.tabfolder, filename);
save(fullname,'Tab5_LTDce'); % save as .mat file



